<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 * @author   howe <howe1995@163.com>
 */
use Hyperf\Context\ApplicationContext;
use Hyperf\Database\Seeders\Seeder;
use Hyperf\DbConnection\Db;
use Hyperf\Filesystem\FilesystemFactory;

use function Hyperf\Support\env;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run()
    {
        $directory = 'migrations/sql';
        // 获取目录中的所有文件和目录
        $files = scandir($directory);
        // 过滤掉当前目录和父目录
        $files = array_diff($files, ['.', '..']);
        $container = ApplicationContext::getContainer();
        /** @var FilesystemFactory $filesystemFactory */
        $filesystemFactory = $container->get(FilesystemFactory::class);
        $disk = $filesystemFactory->get('root');
        foreach ($files as $file) {
            if (pathinfo($file, PATHINFO_EXTENSION) !== 'sql') {
                continue;
            }
            // 获取文件名
            $table = str_replace(env('DB_PREFIX'), '', basename($file, '.sql'));
            Db::statement("truncate `{$table}`");
            // 拼接文件路径
            $file = $directory . '/' . $file;
            $sqlContent = $disk->read($file);
            // 使用分号和回车符分割 SQL 语句
            $statements = preg_split('/;\s*(?:\r\n|\r|\n)/', $sqlContent, -1, PREG_SPLIT_NO_EMPTY);
            // 去除每条语句前后的空白字符
            $statements = array_map('trim', $statements);

            // 过滤掉空字符串
            $statements = array_filter($statements, function ($value) {
                return trim($value) !== '';
            });

            foreach ($statements as $item) {
                Db::insert($item);
            }
            echo "\033[32m  SQL文件 . {$file} . 执行成功 \033[0m" . PHP_EOL;
        }
        echo "\033[32m  数据初始化成功 \033[0m" . PHP_EOL;
    }
}
